import Vue from 'vue'
import VueRouter from 'vue-router'
//import Home from '../views/Home.vue'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'

Vue.use(VueRouter)

const routes = [
  // 路由重定向，让用户访问根目录的时候自动跳转到登录页面
  { path: '/', redirect: '/login' },
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/login', component: Login
  },
  {
    path: '/home', component: Home
  }
]

const router = new VueRouter({
  routes
})
//挂载路由导航守卫
router.beforeEach((to,from,next)=>{
  // to为将要访问的路径
  //from代表从哪个路径跳转而来
  //next是一个函数，表示放行
  //next()放行 next('/login')强制跳转
  if(to.path === '/login') return next();// 判断如果
  const tokenStr = window.sessionStorage.getItem('token')
  if(!tokenStr) return next('/login') //判断token是否为空，如果为空，强制跳转到login页，否则放行
  next()


})
export default router
